<?

/*
*
*   Excalibur Content Management System
*   Copyright © 2008 Egor "Sontan" Kuryanovich
*
*   Based on Explay Engine v2.0 by Golovdinov Alexander
*
*   Official site: www.excms.ru
*   Contact e-mail: support@excms.ru
*
*   GNU General Public License original source:
*   http://www.gnu.org/licenses/gpl-3.0.html
*
*/

if ($EXCMS != "work") {
	exit;
}


$numberart = 15;
$start = 0;
$order = "art_id";
$cols = $_GET['cols'];
$values = $_GET['values'];
$znak = $_GET['znak'];
$id = $_GET['id'];
$znaks = $znak;
$znaks = str_replace ("ravno", "=", $znaks);
$znaks = str_replace ("more", ">", $znaks);
$znaks = str_replace ("less", "<", $znaks);

if (isset($_GET['page']) && $_GET['page'] != "0") $start = (intval ($_GET['page']) - 1) * $numberart;
if (isset($_GET['order'])) $order = $_GET['order'];

if ($_GET['cols '] != "" && $_GET['values'] != "") $cols_s = "AND $cols = '$values'";
if ($_GET['znak'] != "" && isset($_GET['cols']) && $_GET['values'] != "") $cols_s = "AND $cols $znaks '$values'";
if ($_GET['cols'] == "art_author" && $_GET['values'] != "") {
	$author = @mysql_fetch_array (mysql_query ("SELECT user_id FROM ".DB_PEREFIX."_users WHERE user_name = '".$_GET['values']."'"));
	$values_s = $author['user_id'];
	$cols_s = "AND art_author = '$values_s' ";
}

if ($_GET['delete'] == true && isset($_GET['id'])) {
	$delete = @mysql_query ("DELETE FROM ".DB_PEREFIX."_articles WHERE art_id = '$id'");
	@mysql_query ("DELETE FROM ".DB_PEREFIX."_comments WHERE com_category = 'articles' && com_idi = '$id'");
	@mysql_query ("DELETE FROM ".DB_PEREFIX."_rating WHERE rat_cat = 'articles' && com_ed = '$id'");
	if ($delete) site_message ("Статья удалена");
	else site_error ("Ошибка БД или нет такой записи");
}

if ($_GET['public'] == "true" && isset($_GET['id'])) {
	$upd = @mysql_query ("UPDATE ".DB_PEREFIX."_articles SET art_visible = 'on' WHERE art_id = '$id'");
	if ($upd) site_message ("Статья опубликована");
	else site_error ("Ошибка БД");
}

if ($_GET['editor'] == "on" OR $_GET['editor'] == "off") { @mysql_query ("UPDATE site_main SET use_editor = '".$_GET['editor']."'"); $SITE['use_editor'] = $_GET['editor']; }

if ($_GET['mod'] == "save") {
	$header = $_POST['header'];
	$text = $_POST['big_text'];
	$text = replace_symbols ($text);
	$url_name = $_POST['url_name'];
	$visible = $_POST['visible'];
	$author = $GLOBAL_USER['user_id'];
	$cat = $_POST['category'];
	if ($_POST['comment'] == "on") $comm = "on";
	else $comm = "off";
	if ($_POST['publik'] == "on") $publik = "yes";
	else $publik = "no";
	$tags = trim ($_POST['tags']);
	($_POST['auto_tag'] == "true") ? $auto_tag = "yes" : $auto_tag = "no";
	if (substr($tags, strlen($tags)-1) == ",") $tags = substr($tags, strlen($tags)-1);
	if ($_POST['like_page'] == "on") {
		$like_page = "yes";
		$comm = "off";
		$publik = "no";
		$cat = "";
	}
	else $like_page = "no";
	$community = $_POST['community'];
	$error = "";
	
	if ($art_url_name != "") {
		if (@mysql_num_rows (mysql_query ("SELECT * FROM ".DB_PEREFIX."_articles WHERE art_url_name = '$url_name'")) > 1) $error .= "\n<li>Подобный адрес ЧПУ уже существует";
	}
	
	if ($_FILES['image']['name'] != "") {
		if (eregi('[A-Za-z0-9]\.(jpeg|jpg|gif|png|bmp|JPEG|JPG|GIF|PNG|BMP)', $_FILES['image']['name'])) {
			if (!copy($_FILES['image']['tmp_name'], "include/cache/".$_FILES['image']['name'])) $error .= "\n<li>Ошибка при добавлении изоображения!";
		}
		else $error .= "\n<li>Файл не является изоображением!";
	}				
	if ($header == "" || $text == "") $error .= "\n<li>Не заполнены все поля!";
	
	
	
	elseif ($error == "") {
		
		$save = @mysql_query ("INSERT INTO ".DB_PEREFIX."_articles VALUES (0,
			'$cat',
			'$header',
			'$text',
			'$author',
			'".time()."',
			'$comm',
			'$url_name',
			'',
			'$publik',
			'$like_page',
			'$visible',
			'$tags', '0', '',  '0', 
			'$auto_tag')");
		if ($save) { 
			site_message ("Статья сохранена");
			if ($_FILES['image']['name'] != "") {
				save_image ("include/cache/".$_FILES['image']['name'], mysql_insert_id ());
				mysql_query ("UPDATE ".DB_PEREFIX."_articles SET art_image = 'images/articles/".mysql_insert_id ().".jpg' WHERE art_id = '".mysql_insert_id ()."'");
			}
		}
		else { site_error ("Ошибка при сохранении статьи".mysql_error()); /* if (file_exists ("include/cache/".$_FILES['image']['name'])) @unlink ("include/cache/".$_FILES['image']['name']); */ }
	}
	
	else site_error ($error);
}
if ($_GET['mod'] == "edit_save" && isset($_POST['the_id'])) {
	$header = $_POST['header'];
	$text = $_POST['big_text'];
	$tid = $_POST['the_id'];
	$read = $_POST['read'];
	$category = $_POST['category'];
	$url_name = $_POST['url_name'];
	$visible = $_POST['visible'];
	if ($_POST['comment'] == "on") $comm = "on";
	else $comm = "off";
	if ($_POST['publik'] == "on") $publik = "yes";
	else $publik = "no";
	$tags = trim ($_POST['tags']);
	($_POST['auto_tag'] == "true") ? $auto_tag = "yes" : $auto_tag = "no";	
	if (substr($tags, strlen($tags)-1) == ",") $tags = substr($tags, strlen($tags)-1);
	if ($_POST['like_page'] == "on") {
		$like_page = "yes";
		$comm = "off";
		$publik = "no";
		$cat = "";
	}
	else $like_page = "no";
	$community = $_POST['community'];
	
	$error = "";
	$image = "";
	
	if ($art_url_name != "") {
		if (@mysql_num_rows (mysql_query ("SELECT * FROM ".DB_PEREFIX."_articles WHERE art_url_name = '$url_name'")) > 1) $error .= "\n<li>Подобный адрес ЧПУ уже существует";
	}
	
	if ($header == "" || $text == "") $error .= "\n<li>Не заполнены все поля!";
	
	if ($_FILES['image']['name'] != "") {
		if (eregi('[A-Za-z0-9]\.(jpeg|jpg|gif|png|bmp|JPEG|JPG|GIF|PNG|BMP)', $_FILES['image']['name'])) {
			if (copy($_FILES['image']['tmp_name'], "include/cache/".$_FILES['image']['name'])) {
				if (save_image ("include/cache/".$_FILES['image']['name'], $tid)) {
					$image = " art_image = 'images/articles/$tid.jpg', ";
				}
				else $error .= "\n<li>Ошибка при добавлении изоображения!";
			}
			else $error .= "\n<li>Ошибка при добавлении изоображения!";
		}
		else $error .= "\n<li>Файл не является изоображением!";
	}
	
	if ($error == "") {
		$save = @mysql_query ("UPDATE ".DB_PEREFIX."_articles SET art_category = '$category',
			art_header = '$header',
			art_body = '$text',
			art_comments = '$comm',
			art_url_name = '$url_name',
			$image
			art_publik = '$publik',
			art_like_page = '$like_page',
			art_visible = '$visible',
			art_tags = '$tags',
			auto_tag = '$auto_tag' WHERE art_id = '$tid'");
		if ($save) site_message ("Статья сохранена");
		else site_error ("Ошибка при сохранении статьи");
	}
	
	else site_error ($error);
}

if (!isset($_GET['act'])) {	
	print '<ul id="top_nav"><li class="sel"><a href="admin.php">Панель администратора</a></li><li>Управление статьями</li></ul>';
	simple_table ("[ <a href='admin.php?name=articles&act=add'>Добавить статью</a> ] [ <a href='admin.php?name=articles&ed=cat'>Управление разделами</a> ]
	[ <a href='admin.php?name=articles&ed=import'>Импорт статей</a> ] [ <a href='admin.php?name=articles&ed=options'>Настройки</a> ]");
	
	print "\n<script>document.title='Управление статьями - ".$SITE['site_name']."';</script>";
	
	$getsa = @mysql_query ("SELECT * FROM ".DB_PEREFIX."_articles WHERE art_like_page = 'yes' ORDER BY art_id DESC");
	if (@mysql_num_rows ($getsa) == 0) site_error ("Нет статичных статей");
	else {	
		$pages_tr = "";
		while ($ARTSS = @mysql_fetch_array ($getsa)) {	
			$author = @mysql_fetch_array (mysql_query ("SELECT user_name FROM ".DB_PEREFIX."_users WHERE user_id = '".$ARTSS['art_author']."'"));
			
			$pages_tr .= "\n<tr><td class=\"ad_tr\"><a href=\"modules.php?name=articles&cat=".$ARTSS['art_category']."&id=".$ARTSS['art_id']."\" target=\"_blank\">".$ARTSS['art_header']."</a></td>".
			"<td class=\"ad_tr\">".$author['user_name']."</td>".
			"<td class=\"ad_tr\"><center>".format_time($ARTSS['art_date'])."</td>".
			"<td class=\"ad_tr\"><center><a href=\"admin.php?name=articles&act=edit&id=".$ARTSS['art_id']."\"><img src=\"images/edit.gif\" border=\"0\" alt=\"Редактировать\"></a>".
			"<a href=\"javascript:delete_('admin.php?name=articles&delete=true&id=".$ARTSS['art_id']."');\"><img src=\"images/cut.gif\" border=\"0\" alt=\"Удалить\"></a>".
			"<a href=\"modules.php?name=articles&cat=".$ARTSS['art_cat']."&id=".$ARTSS['art_id']."\"><img src=\"images/image.gif\" border=\"0\" alt=\"Просмотр\"></a></td></tr>";
		}
		$pages_table = "\n<table class=\"body_table\" width=\"100%\" cellspacing=\"0\" cellpadding=\"3\">
	<tr>
		<td class=\"top_header_name\"><center>Заголовок</td>
		<td class=\"top_header_name\"><center>Автор</td>
		<td class=\"top_header_name\"><center>Дата</td>
		<td class=\"top_header_name\"><center>Опции</td>
	</tr>$pages_tr
</table><br>";

		past_table ("Управление статичными статьями", $pages_table);
	}
	
	//past_table ("MySQL", $cols_s);
	
	$geta = @mysql_query ("SELECT * FROM ".DB_PEREFIX."_articles WHERE art_like_page = 'no' ".$cols_s." ORDER BY $order DESC LIMIT $start, $numberart");
	if (@mysql_num_rows ($geta) == 0) site_error ("Нет статей");
	else {	
		$art_tr = "";
		$pages_tr = "";
		while ($ARTS = @mysql_fetch_array ($geta)) {	
			$author = @mysql_fetch_array (mysql_query ("SELECT user_name FROM ".DB_PEREFIX."_users WHERE user_id = '".$ARTS['art_author']."'"));

			$color = "";
			$status = "";
			if ($ARTS['art_visible'] == "off") { $color = "bgcolor=\""._DARK_TR_."\""; $status = " (<a href=\"admin.php?name=articles&znak=$znak&cols=$cols&values={$values}&start=$start&public=true&id=".$ARTS['art_id']."\">Опубликовать</a>)"; }
			
			$art_tr .= "\n<tr $color><td class=\"ad_tr\"><a href=\"modules.php?name=articles&cat=".$ARTS['art_category']."&id=".$ARTS['art_id']."\" target=\"_blank\">".$ARTS['art_header']."</a>$status</td>".
			"<td class=\"ad_tr\">".$author['user_name']."</td>".
			"<td class=\"ad_tr\"><center>".$ARTS['art_category']."</td>".
			"<td class=\"ad_tr\"><center>".format_time($ARTS['art_date'])."</td>".
			"<td class=\"ad_tr\"><center><a href=\"admin.php?name=articles&act=edit&id=".$ARTS['art_id']."\"><img src=\"images/edit.gif\" border=\"0\" alt=\"Редактировать\"></a>".
			"<a href=\"javascript:delete_('admin.php?name=articles&delete=true&id=".$ARTS['art_id']."');\"><img src=\"images/cut.gif\" border=\"0\" alt=\"Удалить\"></a>";
		}
		
		$arts_table = "\n<table class=\"body_table\" width=\"100%\" cellspacing=\"0\" cellpadding=\"3\">
	<tr>
		<td class=\"top_header_name\"><center>Название</td>
		<td class=\"top_header_name\"><center><a href=\"admin.php?name=articles&znak=$znak&cols=$cols&values={$values}&order=art_author&start=$start\">Автор</a></td>
		<td class=\"top_header_name\"><center><a href=\"admin.php?name=articles&znak=$znak&cols=$cols&values={$values}&order=art_category&start=$start\">Раздел</a></td>
		<td class=\"top_header_name\"><center><a href=\"admin.php?name=articles&znak=$znak&cols=$cols&values={$values}&order=art_id&start=$start\">Дата</a></td>
		<td class=\"top_header_name\"><center>Опции</td>
	</tr>$art_tr
</table><br>";

		past_table ("Управление статьями", $arts_table);
		print "\n<script>
function delete_ (url_) {
	if (window.confirm('Вы действительно хотите удалить статью?') == true) document.location.href = url_;
}
</script>";
		$count = @mysql_num_rows (mysql_query ("SELECT * FROM ".DB_PEREFIX."_articles WHERE art_like_page = 'no' ".$cols_s));
		//simple_table (past_pages($start, $numberart, $count, "admin.php?name=articles&znak=$znak&cols=$cols&values=$values&order=$order_by"));
		simple_table (past_pages($start, $numberart, $count, "admin.php?name=articles&", "page", "", true));
	}
	select_articles ();
}
if ($_GET['act'] == "add") {
	print '<ul id="top_nav"><li class="sel"><a href="admin.php">Панель администратора</a></li><li><a href="admin.php?name=articles">Управление статьями</a></li><li>Добавление новой статьи</li></ul>';
	simple_table ("[ <a href='admin.php?name=articles&ed=cat'>Управление разделами</a> ] [ <a href='admin.php?name=articles&ed=import'>Импорт статей</a> ] [ <a href='admin.php?name=articles&ed=options'>Настройки</a> ]");
	
	print "\n<script>document.title='Добавить статью - ".$SITE['site_name']."';</script>";
	$cat_ = "";
	$gcat = @mysql_query ("SELECT cat_name, cat_header FROM ".DB_PEREFIX."_art_category");
	while (list($name_1, $header_1) = mysql_fetch_row ($gcat)) {
		$cat_ .= "<option value=\"$name_1\">$header_1</option>";
	}
	add_news ("Добавить статью",
		"name=articles&act=add&mod=save",
		$_POST['header'],
		htmlspecialchars($_POST['big_text']),
		$cat_,
		$_POST['image'],
		$_POST['url_name'],
		$_POST['tags'],
		$_POST['community']);
	come_back ("управленю статьями", "admin.php?name=articles");
}

if ($_GET['act'] == "edit" && isset($_GET['id'])) {
	print '<ul id="top_nav"><li class="sel"><a href="admin.php">Панель администратора</a></li><li><a href="admin.php?name=articles">Управление статьями</a></li><li>Редактирование статьи</li></ul>';
	simple_table ("[ <a href='admin.php?name=articles&act=add'>Добавить статью</a> ] [ <a href='admin.php?name=articles&ed=cat'>Управление разделами</a> ]
	[ <a href='admin.php?name=articles&ed=import'>Импорт статей</a> ] [ <a href='admin.php?name=articles&ed=options'>Настройки</a> ]");
	
	print "\n<script>document.title='Редактировать статью - ".$SITE['site_name']."';</script>";
	$gart = @mysql_query ("SELECT * FROM ".DB_PEREFIX."_articles WHERE art_id = '$id'");
	if ($gart) {	
		$art = mysql_fetch_array ($gart);
		$comm = "";
		$public = "";
		$like_page = "";
		if ($art['art_comments'] == "on") $comm = "checked";
		if ($art['art_publik'] == "yes") $public = "checked";
		if ($art['art_like_page'] == "yes") $like_page = "checked";
		$cat_ = "";
		$gcat = @mysql_query ("SELECT cat_name, cat_header FROM ".DB_PEREFIX."_art_category");
		while (list($name_1, $header_1) = mysql_fetch_row ($gcat)) {
			if ($name_1 == $art['art_category']) $cat_ .= "<option value=\"$name_1\" selected>$header_1</option>";
			else $cat_ .= "<option value=\"$name_1\">$header_1</option>";
		}
		add_news ("Редактировать статью",
			"name=articles&mod=edit_save",
			$art['art_header'],
			$art['art_body'],
			$cat_,
			$art['art_image'],
			$art['art_url_name'],
			$art['art_tags'],
			$art['art_community'],
			$art['art_visible'],
			$comm,
			$public,
			$id,
			$like_page,
			$art['auto_tag']);
	}
	else site_error ("Ошибка БД или нет такой записи");
	come_back ("управленю статьями", "admin.php?name=articles");
}
come_back ("панели администратора", "admin.php");

function select_articles () {
	$form = "<form method=\"GET\" action=\"admin.php?name=articles\">
	<input type=\"hidden\" name=\"name\" value=\"articles\">
	Выбрать статьи где <select name=\"cols\" class=\"form\">
	<option value=\"art_author\">Автор</option>
	<option value=\"art_category\">Категория</option>
	<option value=\"art_read\">Просмотры</option>
	</select> <select name=\"znak\" class=\"form\">
	<option value=\"ravno\">Равняется</option>
	<option value=\"more\">Больше</option>
	<option value=\"less\">Меньше</option>
	</select> <input type=\"text\" class=\"form\" style=\"width:150px\" name=\"values\"> <input type=\"submit\" class=\"button\" value=\"Выбрать\">
	</form>";
	past_table ("Выбор статей", $form);
}

function add_news ($head,
	$act,
	$header,
	$big_text,
	$category,
	$image,
	$url_name,
	$tags,
	$community,
	$visible = "on",
	$comm  = "checked",
	$publik = "checked",
	$id = "",
	$like_page = "",
	$auto_tag = "no") {
	
	global $SITE;
	
	$big_text = replace_symbols ($big_text);
	$big_text = str_replace ("&", "&amp;", $big_text);
	
	if ($visible == "off") $visible = "selected";
	if ($auto_tag == "yes") $auto_tag = "checked";
		
	if ($SITE['use_editor'] == "on" ) {
		print '<!-- TinyMCE -->
<script language="javascript" type="text/javascript" src="include/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
	tinyMCE.init({
		mode : "textareas",
		theme : "advanced",
		plugins : "table,save,advhr,advimage,advlink,iespell,insertdatetime,preview,zoom,searchreplace,contextmenu,paste,directionality,fullscreen",
		theme_advanced_buttons1_add_before : "save,newdocument,separator",
		theme_advanced_buttons1_add : "fontselect,fontsizeselect",
		theme_advanced_buttons2_add : "separator,insertdate,inserttime,preview,zoom,separator,forecolor,backcolor",
		theme_advanced_buttons2_add_before: "cut,copy,paste,pastetext,pasteword,separator,search,replace,separator",
		theme_advanced_buttons3_add_before : "tablecontrols,separator",
		theme_advanced_buttons3_add : "iespell,advhr,separator,separator,ltr,rtl,separator,fullscreen",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		content_css : "example_word.css",
	    plugi2n_insertdate_dateFormat : "%Y-%m-%d",
	    plugi2n_insertdate_timeFormat : "%H:%M:%S",
		external_link_list_url : "example_link_list.js",
		external_image_list_url : "example_image_list.js",
		media_external_list_url : "example_media_list.js",
		file_browser_callback : "fileBrowserCallBack",
		paste_use_dialog : false,
		theme_advanced_resizing : true,
		theme_advanced_resize_horizontal : false,
		theme_advanced_link_targets : "_something=My somthing;_something2=My somthing2;_something3=My somthing3;",
		paste_auto_cleanup_on_paste : true,
		paste_convert_headers_to_strong : false,
		paste_strip_class_attributes : "all",
		paste_remove_spans : false,
		paste_remove_styles : false		
	});

	function fileBrowserCallBack(field_name, url, type, win) {
		// This is where you insert your custom filebrowser logic
		alert("Filebrowser callback: field_name: " + field_name + ", url: " + url + ", type: " + type);

		// Insert new URL, this would normaly be done in a popup
		win.document.forms[0].elements[field_name].value = "someurl.htm";
	}
</script>
<!-- /TinyMCE -->';
}

	
	$form = "\n\n<form style=\"margin:0px\" action=\"admin.php?$act\" method=\"post\" name=\"record\" enctype=\"multipart/form-data\">
<input type=\"hidden\" name=\"the_id\" value=\"$id\">
<table border=\"0\" class=\"main_text\" width=\"100%\" cellspacing=\"0\" cellpadding=\"2\">
	<tr>
		<td colspan=\"2\" align=\"right\">Редактор: ";
	if ($SITE['use_editor'] == "on") $form .=  "<a href=\"admin.php?name=articles&act={$_GET['act']}&editor=off&id=$id\">Простой</a> | Расширенный";
	else $form .=  "Простой | <a href=\"admin.php?name=articles&act={$_GET['act']}&editor=on&id=$id\">Расширенный</a>";
	$form .= "\n</td>
	</tr>
	<tr>
		<td width=\"10%\">Заголовок:</td>
		<td><input type=\"text\" name=\"header\" style=\"width:60%\" class=\"form\" value=\"$header\"></td>
	</tr>
	<tr>
		<td>Название для ЧПУ:</td>
		<td><input type=\"text\" name=\"url_name\" style=\"width:60%\" class=\"form\" value=\"$url_name\"> <a href='javascript:void(0)' onmouseover=\"return overlib('Необязательный параметр, который используется только при включенном ЧПУ. Может содержать только латинские буквы, цифры и знак подчеркиванияю.', BELOW, RIGHT);\" onmouseout=\"return nd();\">?</a></td>
	</tr>
	<tr>
		<td>Изоображение:</td>
		<td><input type=\"file\" name=\"image\" style=\"width:40%\" class=\"form\" /></td>
	</tr>
	<tr>
		<td>Раздел:</td>
		<td><select name=\"category\" style=\"width:60%\" class=\"form\"><option value=\"\" style=\"background-color: #fad2a8\">-- выберите</option>$category</select></td>
	</tr>
	<tr>
		<td>Статус:</td>
		<td><select name=\"visible\" style=\"width:40%\" class=\"form\"><option value=\"on\">Опубликована</option><option value=\"off\" $visible>Отклонена</option></select></td>
	</tr>
	<tr>
		<td colspan=\"2\" style=\"padding-top: 0px\">Текст:<p /><div style=\"width:700px;\">";
		if ($SITE['use_editor'] == "off" ) {
			include "include/editor.html";
			$form .= '<div id="panel" class="panel">
			 <a href="#" onclick="insert_text_b(); return false;" class="buttn"><img src="/images/editor/bold_ru.gif" width="20" height="20" alt=" " title="жирный"></a>
			 <a href="#" onclick="insert_text_i(); return false;" class="buttn"><img src="/images/editor/italic_ru.gif" width="20" height="20" alt=" " title="курсив"></a>
			 <a href="#" onclick="insert_text_u(); return false;" class="buttn"><img src="/images/editor/underline_ru.gif" width="20" height="20" alt=" " title="подчеркнутый"></a>
			 <a href="#" onclick="insert_text_s(); return false;" class="buttn"><img src="/images/editor/strikethrough.gif" width="20" height="20" alt=" " title="зачеркнуть"></a>
			 <a href="#" onclick="insert_text_link(); return false;" class="buttn"><img src="/images/editor/link.gif" width="20" height="20" alt=" " title="вставить ссылку"></a>
			 <a href="#" onclick="insert_text_blockquote(); return false;" class="buttn"><img src="/images/editor/indent.gif" width="20" height="20" alt=" " title="отступ"></a>
			 <a href="#" onclick="insert_text_quote(); return false;" class="buttn"><img src="/images/editor/laquo.gif" width="20" height="20" alt=" " title="кавычки" id="quoteimg"></a>
			 <a href="#" onclick="insert_text_mdash(); return false;" class="buttn"><img src="/images/editor/mdash.gif" width="20" height="20" alt=" " title="тире"></a>
			 <a href="#" onclick="insert_text_img(); return false;" class="buttn"><img src="/images/editor/image.gif" width="20" height="20" alt=" " title="вставить изображение"></a>
			 <a href="#" onclick="insert_text_video(); return false;" class="buttn"><img src="/images/editor/video.gif" width="20" height="20" alt=" " title="вставить видео с YouTube"></a>
			 <a href="#" onclick="text_undo(); return false;" class="buttn"><img src="/images/editor/undo_grey.gif" width="20" height="20" alt=" " title="отменить" id="undoimg"></a>
			</div>';
			
		}
	$form .= "\n<textarea id=\"htmlarea\" class=\"htmlarea\" onkeypress=\"text_clear_undo()\" style=\"height: 300px; width: 100%;\" name=\"big_text\" class=\"form\">$big_text</textarea><br /><span class=\"help\">Для отделение описания от основного текста используйте тег <strong>&lt;cut&gt;</strong>.</span></td>
	</tr>
	<tr>
		<td valign=\"top\"><br />Теги:</td>
		<td><br /><input type=\"text\" style=\"width:60%\" name=\"tags\" id=\"tags\" style=\"width:225px\" class=\"form\" value=\"$tags\" /> <a href='javascript:void(0)' onmouseover=\"return overlib('Введите через запятую небольшое количество ключевых слов, максимально характеризующих статью.', BELOW, RIGHT);\" onmouseout=\"return nd();\">?</a></td>
	</tr>
	<tr>
		<td colspan=\"2\"><span class=\"important_checkbox\"><input onclick=\"if(this.checked==true){document.getElementById('com').disabled=true;document.getElementById('publik').disabled=true;}else{document.getElementById('com').disabled=false;document.getElementById('publik').disabled=false;}\" type=\"checkbox\" name=\"like_page\" value=\"on\" id=\"like_page\" $like_page></span> <label for=\"like_page\">Вести себя как отдельная страница <a href='javascript:void(0)' onmouseover=\"return overlib('В данном случае не будудет выводиться автор, дата создания, рейтинг и прочая информация о статье.', BELOW, RIGHT);\" onmouseout=\"return nd();\">?</a></label></td>
	</tr>
	<tr>
		<td colspan=\"2\"><br /><input type=\"checkbox\" name=\"comment\" value=\"on\" id=\"com\" $comm> <label for=\"com\">Разрешить комментарии</label></td>
	</tr>
	<tr>
		<td colspan=\"2\"><input type=\"checkbox\" name=\"publik\" value=\"on\" id=\"publik\" $publik> <label for=\"publik\">Публиковать в общем списке</label></td>
	</tr>
	<tr>
		<td colspan=\"2\"><br /><input type=\"checkbox\" name=\"auto_tag\" id=\"auto_tag\" value=\"true\" $auto_tag /> <label for=\"auto_tag\">Автоформатирование</label> <a href='javascript:void(0)' onmouseover=\"return overlib('Автоформатирование - автоматическое добавление переноса строки, обработка ВВ-кода и т.д. Желательно отключать при верстке статьи HTML кодом.', BELOW, RIGHT);\" onmouseout=\"return nd();\">?</a></td>
	</tr>	
	<tr>
		<td colspan=\"2\"><br /><span class=\"important_button\"><input style=\"width:240px\" type=\"submit\" name=\"post\" value=\"Сохранить\" class=\"button\"></span> <input onclick='javascript:window.open(\"upload.php\", \"\", \"width=500 height=300 scrollbars\");' type=\"button\" value=\"Загрузить что-нибудь\" class=\"button\"></td>
	</tr>
</table><br />
</form>\n\n";
	if ($SITE['use_editor'] == "off" ) $form .= insert_script ("small_text").insert_script ("big_text");
	
	past_table ($head, $form);
}

function communities ($id) {
	global $db;
	
	$get = $db->query ("SELECT id, header FROM ".DB_PEREFIX."_communities ORDER BY header");
	
	$string = "\n\t<select name=\"community\">\n\t\t<option value=\"0\">нет</option>";
	
	while (list($id_, $title) = $db->fetch_row ($get)) {
		($id == $id_) ? $string .= "\n\t\t<option value=\"$id_\" selected>$title</option>" : $string .= "\n\t\t<option value=\"$id_\">$title</option>";
	}
	
	return $string."\n\t</select>";
}


function save_image ($src, $name) {
	if (!file_exists($src) || $src == "") return false;
	
	$name = "images/articles/$name.jpg";
	
	if(eregi('[A-Za-z0-9]\.(jpeg|jpg|JPEG|JPG)', $src)) {
		$thumbbase = imagecreatefromjpeg($src);
	}
	elseif(eregi('[A-Za-z0-9]\.(gif|GIF)', $src)) {
		$thumbbase = imagecreatefromgif($src);
	}
	elseif(eregi('[A-Za-z0-9]\.(png|PNG)', $src)) {
		$thumbbase = imagecreatefrompng($src);
	}
	elseif(eregi('[A-Za-z0-9]\.(bmp|wbmp|BMP|wbmp)', $src)) {
		$thumbbase = imagecreatefromwbmp($src);
	}
	else exit;
	
	$width = imagesx($thumbbase);
	$height = imagesy($thumbbase);
	
	if ($width > 320 && $height > 240) {
		$k = max($width/320, $height/240);
		$new_width = intval($width / $k);
		$new_height = intval($height / $k);
	}
	else {
		$new_width = $width;
		$new_height = $height;
	}
	
	$thumb = imagecreatetruecolor ($new_width, $new_height);
	imagecopyresampled($thumb, $thumbbase, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
	if (imagejpeg($thumb, $name, 70)) {
		imagedestroy($thumb);
		imagedestroy($thumbbase);
		@unlink ($src);
		return true;
	}
	return false;
}
